package tech.mhuang.pacebox.sms.inteceptor;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import tech.mhuang.pacebox.core.chain.BaseChain;
import tech.mhuang.pacebox.core.chain.BaseInterceptor;
import tech.mhuang.pacebox.core.exception.BusinessException;
import tech.mhuang.pacebox.core.util.ObjectUtil;
import tech.mhuang.pacebox.sms.BaseSmsHandler;
import tech.mhuang.pacebox.sms.domain.SmsSendRequest;
import tech.mhuang.pacebox.sms.domain.SmsSendResult;

import java.util.Map;

/**
 * 短信发送接口拦截
 *
 * @author mhuang
 * @since 1.0.0
 */
public interface SmsSendInterceptor extends BaseInterceptor<BaseChain<SmsSendRequest, SmsSendResult>, SmsSendResult> {

    /**
     * 默认处理
     *
     * @author mhuang
     * @since 1.0.0
     */
    @Slf4j
    class Standard implements SmsSendInterceptor {

        /**
         * 具体配置了多少个短信处理器(发送时进行指定）
         */
        private final Map<String, BaseSmsHandler> smsHandlerMap;

        public Standard(Map<String, BaseSmsHandler> smsHandlerMap) {
            this.smsHandlerMap = smsHandlerMap;
        }

        @Override
        public SmsSendResult interceptor(BaseChain<SmsSendRequest, SmsSendResult> chain) {
            SmsSendRequest request = chain.request();
            log.info("开始发送短信====request:{}", JSON.toJSONString(request));
            SmsSendResult result;
            BaseSmsHandler smsHandler = smsHandlerMap.get(request.getType());
            if (ObjectUtil.isEmpty(smsHandler)) {
                result = SmsSendResult.builder().success(false)
                        .message("找不到发送的短信配置")
                        .throwable(new BusinessException(500, "找不到发送的短信配置")).build();
            } else {
                result = smsHandler.send(request);
            }
            log.info("短信发送结果====request:{},response:{}", JSON.toJSONString(request), JSON.toJSONString(result));
            return result;
        }
    }
}